package com.xiaoai.io.nio3Selector;

import com.sun.org.apache.bcel.internal.generic.Select;
import org.bson.ByteBuf;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @Author
 * @Date 2021-09-11 23:48
 */
public class Server {
    public static void main(String[] args){
        System.out.println("=====服务端启动=====");
        try {
            // 获取通道
            ServerSocketChannel ssChannel = ServerSocketChannel.open();
            // 切换非阻塞
            ssChannel.configureBlocking(false);
            // 绑定端口
            ssChannel.bind(new InetSocketAddress(9999));
            // 获取选择器
            Selector selector = Selector.open();
            // 通过注册选择器上
            ssChannel.register(selector, SelectionKey.OP_ACCEPT);
            // 使用选择器轮询就绪好的事件
            while (selector.select() > 0){
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()){
                    // 提取当前事件
                    SelectionKey sk = it.next();
                    // 判断事件具体是什么
                    if (sk.isAcceptable()){
                        // 获取当前接入客户端通道
                        SocketChannel schannel = ssChannel.accept();
                        // 切换非阻塞模式
                        schannel.configureBlocking(false);
                        // 将本客户端通道注册到选择器
                        schannel.register(selector,SelectionKey.OP_READ);
                    }else if (sk.isReadable()){
                        // 获取当前选择器上的读就绪事件
                        SocketChannel sChannel = (SocketChannel) sk.channel();
                        // 读取事件
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        int len = 0;
                        while ((len = sChannel.read(buf)) > 0){
                            buf.flip();
                            System.out.println(new String(buf.array(),0,len));
                            buf.clear();
                        }
                    }
                    // 取消选择键 SelectionKey
                    it.remove();

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
